#include "pch.h"
#include "AudioInterfaceActivator.h"

using namespace GuitarFX_Audio;

HRESULT CAudioInterfaceActivator::ActivateCompleted(IActivateAudioInterfaceAsyncOperation  *pAsyncOp)
{
	HRESULT hr = S_OK, hr2 = S_OK;
	ComPtr<IUnknown> clientUnk;
	ComPtr<IAudioClient2> audioClient2;

	// Get the audio activation result as IUnknown pointer
	hr2 = pAsyncOp->GetActivateResult(&hr, &clientUnk);

	// Report activation failure
	if (FAILED(hr))
	{
		m_ActivateCompleted.set_exception(ref new Platform::COMException(hr));
		goto exit;
	}

	// Report failure to get activate result
	if (FAILED(hr2))
	{
		m_ActivateCompleted.set_exception(ref new Platform::COMException(hr));
		goto exit;
	}

	// Query for the activated IAudioClient2 interface
	hr = clientUnk.As(&audioClient2);

	if (FAILED(hr))
	{
		m_ActivateCompleted.set_exception(ref new Platform::COMException(hr));
		goto exit;
	}

	// Set the completed event and return success
	m_ActivateCompleted.set(audioClient2);

exit:
	return hr;
}

task<ComPtr<IAudioClient2>> CAudioInterfaceActivator::ActivateAsync(LPCWCHAR deviceId)
{
	ComPtr<CAudioInterfaceActivator> activator = Make<CAudioInterfaceActivator>();
	ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;

	HRESULT hr = ActivateAudioInterfaceAsync(
		deviceId,
		__uuidof(IAudioClient2),
		nullptr,
		activator.Get(),
		&asyncOp);

	if (FAILED(hr))
		throw ref new Platform::COMException(hr);

	// Wait for the activate completed event and return result
	return create_task(activator->m_ActivateCompleted);

}

